package com.bjpowernode.boss.common.exception.handler;

import com.bjpowernode.boss.common.enums.ResponseCode;
import com.bjpowernode.boss.common.exception.BossException;
import com.bjpowernode.boss.mvc.models.AjaxResult;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.validation.BindException;
import org.springframework.validation.BindingResult;
import org.springframework.validation.FieldError;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;

import java.util.Arrays;
import java.util.List;

/**
 * 全局异常处理
 *
 * @author yu
 * @date 2024/7/7  20:49
 */

@RestControllerAdvice
public class GlobalExceptionHandler {
    Logger logger = LoggerFactory.getLogger(GlobalExceptionHandler.class) ;

    @ExceptionHandler({BossException.class})
    public AjaxResult doBossException(BossException e) {
        e.printStackTrace();

        ResponseCode responseCode = e.getResponseCode() ;
        logger.error("发送了BossException异常，code：{}，msg：{}", responseCode.getNumber(), responseCode.getMsg());

        AjaxResult ajaxResult = AjaxResult.FAIL(responseCode) ;
        return ajaxResult ;
    }

    @ExceptionHandler(BindException.class)
    public AjaxResult doBeanValidation(BindException e) {
        e.printStackTrace();

        // 获得bindingResult
        BindingResult bindingResult = e.getBindingResult() ;
        // 创建一个列表来收集所有的错误信息，因为只对字段进行检查，所以只存在Fielderror
        List<FieldError> fieldErrorList = bindingResult.getFieldErrors() ;

        // 拼接字符串
        StringBuilder stringBuilder = new StringBuilder() ;
        fieldErrorList.forEach(fieldError -> {
            stringBuilder.append(fieldError.getDefaultMessage()).append(" ") ;
        });

        AjaxResult ajaxResult = new AjaxResult() ;
        ajaxResult.setCode(ResponseCode.REQUEST_PARAM_ERR.getNumber());
        ajaxResult.setMsg(ResponseCode.REQUEST_PARAM_ERR.getMsg() + "，原因是：" + stringBuilder.toString());
        ajaxResult.setData("");

        return ajaxResult ;
    }

}
